const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  console.log('📋 获取待审核施工队伍列表')
  
  try {
    const { page = 1, pageSize = 10 } = event
    
    // 计算跳过的记录数
    const skip = (page - 1) * pageSize
    
    // 获取待审核的队伍总数
    const countResult = await db.collection('construction_teams')
      .where({
        auditStatus: 'pending'
      })
      .count()
    
    const totalCount = countResult.total
    
    // 获取待审核的队伍列表
    const teamsResult = await db.collection('construction_teams')
      .where({
        auditStatus: 'pending'
      })
      .orderBy('submitTime', 'asc') // 按提交时间升序，先提交的先审核
      .skip(skip)
      .limit(pageSize)
      .get()
    
    const teams = teamsResult.data.map(team => ({
      _id: team._id,
      id: team.id,
      name: team.name,
      type: team.type,
      typeName: team.typeName,
      phone: team.phone,
      location: team.location,
      category: team.category,
      categoryName: team.categoryName,
      experience: team.experience,
      description: team.description,
      specialties: team.specialties || [],
      certifications: team.certifications || [],
      avatar: team.avatar,
      submitTime: team.submitTime,
      createTime: team.createTime,
      // 个人师傅特有字段
      realName: team.realName,
      idCard: team.idCard,
      // 公司特有字段
      companyName: team.companyName,
      businessLicense: team.businessLicense,
      legalRepresentative: team.legalRepresentative,
      registeredCapital: team.registeredCapital,
      companyAddress: team.companyAddress
    }))
    
    console.log(`✅ 获取到 ${teams.length} 个待审核队伍`)
    
    return {
      success: true,
      data: {
        teams: teams,
        pagination: {
          page: page,
          pageSize: pageSize,
          totalCount: totalCount,
          totalPages: Math.ceil(totalCount / pageSize),
          hasMore: skip + teams.length < totalCount
        }
      }
    }
    
  } catch (error) {
    console.error('❌ 获取待审核队伍列表失败:', error)
    return {
      success: false,
      error: error.message || '获取列表失败'
    }
  }
}
